package Leetcode250618.array;

import Leetcode250618.ListNode;

/**
 * @description:  leetcode2 两数相加
 * @author: ChenYawei
 * @date: 2025/6/18  16:37
 */
public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int add = 0;
        while (l1 != null || l2 != null) {
            int num1 = l1 != null ? l1.val : 0;
            int num2 = l2 != null ? l2.val : 0;
            int sum = num1 + num2 + add;
            int num = sum % 10;
            add = sum / 10;
            if (head == null) {
                head = tail = new ListNode(num);
            } else {
                tail.next = new ListNode(num);
            }
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
            tail = tail.next;
        }
        if (add != 0) {
            tail.next = new ListNode(add);
        }
        return head;
    }

}
